package cn.htsyb.synergy.maker.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;

public class PropertyUtil {
    private static final String MAKER_PROPERTIES = "classpath:maker.properties";
    private static final String SPLIT_CHAR = ",";
    private static Properties props;

    static {
        loadProps();
    }

    synchronized static private void loadProps() {
        props = new Properties();
        try (InputStream in = ResourceUtil.getAsInputStream(MAKER_PROPERTIES)) {
            props.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getString(String key) {
        if (null == props) {
            loadProps();
        }
        return props.getProperty(key);
    }

    public static String getString(String key, String defaultValue) {
        if (null == props) {
            loadProps();
        }
        return props.getProperty(key, defaultValue);
    }

    public static Map getMap() {
        return props;
    }

    public static Boolean getBoolean(String key) {
        String value = getString(key);
        return value != null ? Boolean.valueOf(value) : null;
    }

    public static Boolean getBoolean(String key, Boolean defaultValue) {
        String value = getString(key);
        return value != null ? Boolean.valueOf(value) : defaultValue;
    }

    public static Integer getInteger(String key) {
        String value = getString(key);
        return value != null ? Integer.valueOf(value) : null;
    }

    public static Integer getInteger(String key, Integer defaultValue) {
        String value = getString(key);
        return value != null ? Integer.valueOf(value.trim()) : defaultValue;

    }

    public static String[] getStringArray(String key) {
        String value = getString(key);
        return value != null ? value.split(SPLIT_CHAR) : null;

    }

    public static String[] getStringArray(String key, String[] defaultValue) {
        String value = getString(key);
        return value != null ? value.split(SPLIT_CHAR) : defaultValue;

    }

    public Map<Object, Object> getPropsAsMap(String propsPath) {
        Properties propsEntry = new Properties();
        try (InputStream in = ResourceUtil.getAsInputStream(MAKER_PROPERTIES)) {
            propsEntry.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return propsEntry;
    }

}
